

import java.io.IOException;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessionbeans.ProfileBeanRemote;

import entities.RegisteredUser;
import entities.Declares;

/**
 * Servlet implementation class PersonalServlet
 */
public class PersonalServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PersonalServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		InitialContext context;
		RegisteredUser user;
		List<Declares> abilities;
		String userId = (String) request.getSession().getAttribute("userId");
		
		if (userId != null) {
			try {
				context = new InitialContext();
				Object ref = context.lookup("ProfileBeanRemote");
				ProfileBeanRemote profileBean = (ProfileBeanRemote)PortableRemoteObject.narrow(ref, ProfileBeanRemote.class);		
				user = profileBean.getUser(userId);
				abilities = profileBean.getAbilities(userId);
				request.getSession().setAttribute("user", user);
				request.getSession().setAttribute("userabilities", abilities);
				response.sendRedirect((String)request.getSession().getAttribute("redirected"));
			} catch (NamingException e) {
				System.out.println("Naming Exception");
				e.printStackTrace();
			}
		}
		else {
			request.getSession().setAttribute("redirected", "Index.jsp");
			request.getSession().setAttribute("message","Session expired. Redirecting to login page...");
			response.sendRedirect("Message.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
